import axios, { AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { parseCookies, setCookie, destroyCookie } from "nookies";
import { alert } from "../components/alert"; // 是我封装的alert组件
// 需要走服务端的接口
const serverUrl: string[] = []; // 定义需要走服务端的接口
const service = axios.create({
  baseURL: "", // 获取环境变量配置
  timeout: 10000, // 设置超时时间
}); // Request interceptor

// 自定义传入的参数
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const cookies = parseCookies(); // token判断
    if (cookies?.token) {
      config.headers["Authorization"] = "Bearer " + cookies?.token;
    }
    // 是否需要走服务端
    if (serverUrl.includes(config.url || "")) {
      config.baseURL = process.env.NEXT_PUBLIC_API;
    }
    config.headers["Content-Type"] = "application/json";

    return config;
  },
  (error: any) => {
    Promise.reject(error);
  }
); // Response interceptors

service.interceptors.response.use(
  async (response: AxiosResponse) => {
    const code = response.data.code;
    if (code === 401) {
      destroyCookie(null, "token");
      if (typeof window !== "undefined") {
        alert("error", "登录状态已过期，请重新登录");
        if (typeof window !== "undefined") {
          window.location.href = "/login";
        }
      }
    } else if (code === 6401) {
      destroyCookie(null, "token");
      return false;
    } else if (code === 400 || code === 403) {
      if (typeof window !== "undefined") {
        alert("error", response.data.msg);
      }
    } else {
      return response.data;
    }
  },
  (error: any) => {
    if (error?.response?.status === 401 || error?.response?.status === 403) {
      destroyCookie(null, "token");
      if (typeof window !== "undefined") {
        window.location.href = "/login";
      }
      return;
    } else if (error?.code === "ERR_CANCELED") {
      return;
    } else {
      return Promise.reject(error);
    }
  }
);

export default service;
